package webhook

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"time"

	mhttp "github.com/meilihao/golib/v2/http"
	"github.com/meilihao/golib/v2/log"
)

type WebhookCaller struct {
	call func()
}

func NewWebhookCaller(call func()) *WebhookCaller {
	return &WebhookCaller{
		call: call,
	}
}

func (c *WebhookCaller) PostToWebhooks(hooks []WebhookVO, body []byte) {
	for _, hook := range hooks {
		req, err := http.NewRequest(http.MethodPost, hook.Url, bytes.NewReader(body))
		if err != nil {
			log.Glog.Error(err.Error())
			continue
		}
		req.Header.Set("Content-Type", "application/json; charset=utf-8")

		resp, err := mhttp.Do(context.TODO(), &mhttp.Option{
			Req:           req,
			RetryCount:    5,
			RetryWaitTime: time.Second,
		})
		if err != nil {
			log.Glog.Error(err.Error())
			continue
		}
		if !(resp.Code >= 200 && resp.Code < 300) {
			log.Glog.Warn(fmt.Sprintf("unable to call the webhook[uuid:%s, name:%s, url:%s], status code: %d, body: %s",
				hook.Uuid, hook.Name, hook.Url, resp.Code, string(resp.Body)))
		}
	}
}

func (c *WebhookCaller) Call() {
	c.call()
}
